package com.ct.onlinemusic.service;

import com.ct.onlinemusic.mapper.MusicInfoMapper;
import com.ct.onlinemusic.model.MusicInfo;
import com.ct.onlinemusic.model.UserInfo;
import com.ct.onlinemusic.tools.Constant;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MusicService {
    @Value("${music.local.path}")
    private String SAVE_PATH;
    @Autowired
    private MusicInfoMapper musicInfoMapper;
    public Integer isUpload (String singer, MultipartFile file, HttpSession session) {
        log.error(file.getOriginalFilename());
        String fileName = file.getOriginalFilename();
        String path = SAVE_PATH + '/' + fileName;
        File newFile = new File(path);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            log.error("发生错误: ", e);
            return -1;
        }
        String title = fileName.substring(0, fileName.lastIndexOf("."));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = dateFormat.format(new Date());
        String url = "/music/get?path=" + title;
        Integer status = 1;
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        Integer userId = userInfo.getId();
        int ret = musicInfoMapper.insert(title, singer, time, url, status, userId);
        if (ret == 1) {
            return 1;
        } else {
            newFile.delete();
            return 0;
        }
    }

    public Integer deleteById(Integer id) {
        MusicInfo musicInfo = new MusicInfo();
        musicInfo.setId(id);
        musicInfo.setStatus(0);
        return musicInfoMapper.updateMusicById(musicInfo);
    }

    public Integer deleteSel(List<Integer> ids) {
        log.error("一键删除ids:{}", ids);
        return musicInfoMapper.updateMusicSel(ids);
    }

    public List<MusicInfo> findMusicByTitle(String title) {
        return musicInfoMapper.findMusicByTitle(title);
    }
}
